package com.universal.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * IP 地址
 *
 * @author: austin
 * @date: 2022/11/13 22:21
 */
public class IPUtils {

    private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

    private static final String UNKNOWN = "unknown";

    private IPUtils() {
    }

    /**
     * 获取IP地址
     *
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     **/
    public static String getIpAddress(HttpServletRequest request) {
        String XFor = null;
        try {
            String Xip = request.getHeader("X-Real-IP");
            XFor = request.getHeader("X-Forwarded-For");
            if (StringUtils.isNotEmpty(XFor) && !UNKNOWN.equalsIgnoreCase(XFor)) {
                //多次反向代理后会有多个ip值，第一个ip才是真实ip
                int index = XFor.indexOf(",");
                if (index != -1) {
                    return XFor.substring(0, index);
                } else {
                    return XFor;
                }
            }
            XFor = Xip;
            if (StringUtils.isNotEmpty(XFor) && !UNKNOWN.equalsIgnoreCase(XFor)) {
                return XFor;
            }
            if (StringUtils.isBlank(XFor) || UNKNOWN.equalsIgnoreCase(XFor)) {
                XFor = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(XFor) || UNKNOWN.equalsIgnoreCase(XFor)) {
                XFor = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(XFor) || UNKNOWN.equalsIgnoreCase(XFor)) {
                XFor = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(XFor) || UNKNOWN.equalsIgnoreCase(XFor)) {
                XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(XFor) || UNKNOWN.equalsIgnoreCase(XFor)) {
                XFor = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("IPUtils get ip address error!", e);
        }
        return XFor;
    }

}
